package com.huahai.security.core.authentication.handler;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.huahai.security.core.properties.StatusCodeEnum;
import com.huahai.security.core.supports.ResultResponse;
import com.huahai.security.core.util.JwtTokenUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @Author: Jun
 * @Date: 2020/7/17
 *
 * 自定义用户登录认证成功处理器
 * 生成token返回给用户
 */
@Component
public class CustomAuthenticationSuccessHandler extends SavedRequestAwareAuthenticationSuccessHandler {

    private final Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    private JwtTokenUtils jwtTokenUtils;

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        UserDetails user = (UserDetails) authentication.getPrincipal();

        List<String> roles = user.getAuthorities().stream()
                .map(GrantedAuthority::getAuthority)
                .collect(Collectors.toList());

        HashMap<String,Object> map = new HashMap<>(16);
        map.put("rol",roles);

        String token = jwtTokenUtils.createToken(user.getUsername(),map);

        ObjectMapper objectMapper = new ObjectMapper();
        Map<String,Object> userMap = new HashMap<>(16);
        userMap.put("username",user.getUsername());
        userMap.put("token",token);

        response.setContentType("application/json;charset=UTF-8");
        response.setStatus(HttpStatus.OK.value());
        response.getWriter().write(objectMapper.writeValueAsString(
                ResultResponse.build(StatusCodeEnum.HSC200000.getCode(), StatusCodeEnum.HSC200000.getMessage(),userMap)
        ));
    }
}
